import { Injectable } from '@nestjs/common';
// import { CreateCenterDto } from './dto/create-center.dto';
// import { UpdateCenterDto } from './dto/update-center.dto';

import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CenterInfoDocumentType } from '../schema/Center/Center_Schema';

@Injectable()
export class CenterService {
  constructor(
    @InjectModel('Center_Info')
    private CenterInfoModel: Model<CenterInfoDocumentType>,
  ) {}

  async createCenterInfo(body: any) {
    const center_info = new this.CenterInfoModel(body);
    return center_info.save();
  }

  async getCenterInfo(query: any) {
    const { page, limit, price, cpu_slot, memory_type, order } = query;

    let sort = {};
    if (order) {
      sort = { price: parseInt(order) };
    } else {
      sort = {};
    }

    const filter: any = {};
    if (cpu_slot) {
      filter.cpu_slot = cpu_slot;
    }
    if (memory_type) {
      filter.memory_type = memory_type;
    }
    if (price) {
      if (price.min && !price.max) {
        filter.price = { $gte: price.min };
      } else if (!price.min && price.max) {
        filter.price = { $lte: price.max };
      } else if (price.min && price.max) {
        filter.price = { $gte: price.min, $lte: price.max };
      }
    }

    //执行查询
    const result = await this.CenterInfoModel.find(filter)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort(sort)
      .exec();
    return {
      code: 200,
      msg: 'success',
      data: {
        result,
        total: await this.CenterInfoModel.countDocuments(filter),
      },
    };
  }

  async getCenterInfoById(id: string) {
    const result = await this.CenterInfoModel.findById(id).exec();
    console.log(result);

    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  async updateCenterInfo(id: string, body: any) {
    const result = await this.CenterInfoModel.findByIdAndUpdate(id, body, {
      new: true,
    }).exec();

    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  async deleteCenterInfo(id: string) {
    const result = await this.CenterInfoModel.findByIdAndDelete(id).exec();

    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  async getAllCenterInfo() {
    const result = await this.CenterInfoModel.find()
      .select('score price id')
      .exec();

    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }
}
